import React, { useRef, useEffect, useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  Image,
  ScrollView,
  TouchableOpacity,
  ImageBackground,
  Dimensions,
  Animated,
  NativeSyntheticEvent,
  NativeScrollEvent,
  StatusBar,
} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import SignInModal from '../wyk/SignInModal';

const { width } = Dimensions.get('window');

interface TitleWithLinesProps {
  title: string;
}

const HomeScreen = ({navigation}: any) => {
  const scrollX = useRef(new Animated.Value(0)).current;
  const [currentIndex, setCurrentIndex] = useState(0);
  const flatListRef = useRef<ScrollView>(null);
  const [isSignInModalVisible, setIsSignInModalVisible] = useState(false);

  const favoriteRooms = [
    {
      id: 1,
      title: '豪华大床房',
      price: 158,
      image: require('./image/room1.jpg'),
    },
    {
      id: 2,
      title: '大床房',
      price: 128,
      image: require('./image/room2.jpg'),
    },
    {
      id: 3,
      title: '双床房',
      price: 138,
      image: require('./image/room3.jpg'),
    },
    {
      id: 4,
      title: '套房',
      price: 298,
      image: require('./image/room1.jpg'),
    },
    {
      id: 5,
      title: '海景房',
      price: 498,
      image: require('./image/luxury-room.jpg'),
    },
  ];

  useEffect(() => {
    const timer = setInterval(() => {
      const nextIndex = (currentIndex + 1) % favoriteRooms.length;
      flatListRef.current?.scrollTo({
        x: nextIndex * width * 0.8,
        animated: true,
      });
      setCurrentIndex(nextIndex);
    }, 3000);

    return () => clearInterval(timer);
  }, [currentIndex, favoriteRooms.length]);

  const recommendedRooms = [
    {
      id: 1,
      title: '豪华大床房-海景人气爆款',
      tags: ['优选', '舒适', '海景'],
      price: 498,
      image: require('./image/luxury-room.jpg'),
    },
    {
      id: 2,
      title: '豪华大床房-赠双人早餐',
      tags: ['优选', '舒适', '爆款'],
      price: 598,
      image: require('./image/room1.jpg'),
    },
    {
      id: 3,
      title: '大床房-优惠又实惠',
      tags: ['优选', '舒适', '爆款'],
      price: 298,
      image: require('./image/room2.jpg'),
    },
    {
      id: 4,
      title: '双床房-酒店必备',
      tags: ['优选', '舒适', '爆款'],
      price: 268,
      image: require('./image/room3.jpg'),
    },
    {
      id: 5,
      title: '豪华大床房-海景人气爆款',
      tags: ['优选', '舒适', '爆款'],
      price: 698,
      image: require('./image/luxury-room.jpg'),
    },
  ];

  const handleSignIn = () => {
    // 这里添加签到逻辑
    setIsSignInModalVisible(false);
    // TODO: 调用签到API
  };

  const menuItems = [
    { icon: 'shopping-bag', text: '专享礼包', onPress: () => navigation.navigate('Yve') },
    { icon: 'today', text: '每日签到', onPress: () => setIsSignInModalVisible(true) },
    { icon: 'local-offer', text: '优惠券', onPress: () => navigation.navigate('Youhui') },
    { icon: 'redeem', text: '我的订单', onPress: () => {} },
    { icon: 'support-agent', text: '积分商城', onPress: () => navigation.navigate('PointsMall') },
  ];

  const TitleWithLines: React.FC<TitleWithLinesProps> = ({ title }) => (
    <View style={styles.titleContainer}>
      <View style={styles.line} />
      <Text style={styles.titleText}>{title}</Text>
      <View style={styles.line} />
    </View>
  );

  return (
    <ScrollView style={styles.container}>
      {/* Banner section */}
      <ImageBackground
        source={require('./image/hotel-banner.jpg')}
        style={styles.banner}>
        {/* Header */}
        <View style={styles.header}>
          <Text style={styles.headerTitle}>宏达万枫酒店</Text>
        </View>

        {/* Banner content */}
        <View>
          <View style={styles.bannerTitleContainer}>
            <Text style={styles.bannerTitle}>万枫酒店欢迎您</Text>
          </View>
        </View>
      </ImageBackground>

      {/* Banner content */}
      <View style={styles.bannerContent}>
          <TouchableOpacity 
            style={styles.couponContainer}
            onPress={() => navigation.navigate('Youhui')}>
            <View style={styles.couponLeft}>
              <View style={styles.couponIconContainer}>
              <Image source={require('./image/coupon-icon.png')} style={styles.couponIcon}/>
              </View>
              <View style={styles.couponTextContainer}>
                <Text style={styles.couponLabel}>满</Text>
                <Text style={styles.couponAmount}>¥500</Text>
                <Text style={styles.couponLabel}>减</Text>
                <Text style={styles.couponAmount}>¥50</Text>
              </View>
            </View>
            <View style={styles.couponRight}>
              <Text style={styles.couponButtonText}>使用专享</Text>
              <Icon name="chevron-right" size={16} color="#999" />
            </View>
          </TouchableOpacity>
        </View>

      {/* 菜单部分 */}
      <View style={styles.menuContainer}>
        {menuItems.map((item, index) => (
          <TouchableOpacity 
            key={index} 
            style={styles.menuItem}
            onPress={item.onPress}
          >
            <View style={styles.iconContainer}>
              <Icon name={item.icon} size={24} color="#1DBFB4" />
            </View>
            <Text style={styles.menuText}>{item.text}</Text>
          </TouchableOpacity>
        ))}
      </View>

      {/* 猜你喜欢部分 */}
      <View style={styles.favoriteSection}>
        <TitleWithLines title="猜你喜欢" />
        <ScrollView
          ref={flatListRef}
          horizontal
          pagingEnabled
          showsHorizontalScrollIndicator={false}
          onScroll={Animated.event(
            [{ nativeEvent: { contentOffset: { x: scrollX } } }],
            { useNativeDriver: false },
          )}
          scrollEventThrottle={16}>
          {favoriteRooms.map((room, index) => (
            <TouchableOpacity
              key={room.id}
              style={styles.favoriteRoomCard}
              activeOpacity={0.8}
              onPress={() => navigation.navigate('RoomDetail', { roomId: room.id })}>
              <Image source={room.image} style={styles.favoriteRoomImage} />
              <View style={styles.favoriteRoomInfo}>
                <Text style={styles.favoriteRoomTitle}>{room.title}</Text>
                <Text style={styles.favoriteRoomPrice}>¥ {room.price}</Text>
              </View>
            </TouchableOpacity>
          ))}
        </ScrollView>
        <View style={styles.paginationContainer}>
          {favoriteRooms.map((_, index) => {
            const inputRange = [
              (index - 1) * width * 0.8,
              index * width * 0.8,
              (index + 1) * width * 0.8,
            ];
            const dotWidth = scrollX.interpolate({
              inputRange,
              outputRange: [8, 16, 8],
              extrapolate: 'clamp',
            });
            const opacity = scrollX.interpolate({
              inputRange,
              outputRange: [0.3, 1, 0.3],
              extrapolate: 'clamp',
            });
            return (
              <Animated.View
                key={index}
                style={[
                  styles.dot,
                  { width: dotWidth, opacity },
                  currentIndex === index && styles.activeDot,
                ]}
              />
            );
          })}
        </View>
      </View>

      {/* 今日推荐 */}
      <View style={styles.sectionContainer}>
        <Text style={styles.sectionTitle}>今日推荐</Text>
        {recommendedRooms.map(room => (
          <TouchableOpacity 
            key={room.id} 
            style={styles.recommendedCard}
            onPress={() => navigation.navigate('RoomDetail', { roomId: room.id })}>
            <Image source={room.image} style={styles.recommendedImage} />
            <View style={styles.recommendedInfo}>
              <Text style={styles.recommendedTitle}>{room.title}</Text>
              <View style={styles.tagsContainer}>
                {room.tags.map((tag, index) => (
                  <View key={index} style={styles.tag}>
                    <Text style={styles.tagText}>{tag}</Text>
                  </View>
                ))}
              </View>
              <View style={styles.priceContainer}>
                <Text style={styles.price}>¥{room.price}</Text>
                <TouchableOpacity 
                  style={styles.bookButton}
                  onPress={() => navigation.navigate('RoomDetail', { roomId: room.id })}>
                  <Text style={styles.bookButtonText}>预订</Text>
                </TouchableOpacity>
              </View>
            </View>
          </TouchableOpacity>
        ))}
      </View>

      <SignInModal
        visible={isSignInModalVisible}
        onClose={() => setIsSignInModalVisible(false)}
        onSignIn={handleSignIn}
      />
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  titleContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 20,
    marginVertical: 15,
  },
  bannerTitleContainer: {
    marginTop: 80,
  },
  titleText: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#333',
    marginHorizontal: 10,
  },
  couponLeft: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  couponIcon: {
    width: 20,
    height: 20,
    marginRight: 8,
  },
  couponRight: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingLeft: 190
  },
  headerTitle: {
    color: '#fff',
    fontSize: 18,
    fontWeight: '600',
  },
  couponTextContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  line: {
    flex: 1,
    height: 1,
    backgroundColor: '#E8E8E8',
  },
  favoriteSection: {
    backgroundColor: '#fff',
    paddingVertical: 10,
  },
  favoriteRoomCard: {
    width: width * 0.8,
    marginHorizontal: 10,
    borderRadius: 8,
    backgroundColor: '#fff',
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.1,
    shadowRadius: 3.84,
    elevation: 5,
  },
  favoriteRoomImage: {
    width: '100%',
    height: 120,
    borderTopLeftRadius: 8,
    borderTopRightRadius: 8,
  },
  favoriteRoomInfo: {
    padding: 10,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  bannerContent: {
    flex: 1,
    justifyContent: 'space-between',
    padding: 15,
  },
  favoriteRoomTitle: {
    fontSize: 16,
    color: '#333',
  },
  favoriteRoomPrice: {
    fontSize: 18,
    color: '#ff4d4f',
    fontWeight: 'bold',
  },
  paginationContainer: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 10,
  },
  couponIconContainer: {
    width: 24,
    height: 24,
    borderRadius: 12,
    backgroundColor: '#FFF0F0',
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 8,
  },
  dot: {
    height: 8,
    borderRadius: 4,
    backgroundColor: '#1DBFB4',
    marginHorizontal: 4,
  },
  activeDot: {
    backgroundColor: '#1DBFB4',
  },
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  banner: {
    height: 170,
    justifyContent: 'flex-end',
  },
  bannerTitle: {
    color: '#fff',
    fontSize: 24,
    fontWeight: 'bold',
    textAlign: 'center',
    marginBottom: 10,
  },
  couponContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: 'rgba(255,255,255,0.9)',
    padding: 10,
    borderRadius: 5,
  },
  couponLabel: {
    fontSize: 14,
    color: '#666',
    marginHorizontal: 2,
  },
  couponAmount: {
    fontSize: 14,
    color: '#FF6B6B',
    fontWeight: '600',
  },
  couponText: {
    color: '#ff4d4f',
    fontSize: 16,
    marginRight: 10,
  },
  couponButton: {
    backgroundColor: '#ff4d4f',
    paddingHorizontal: 10,
    paddingVertical: 5,
    borderRadius: 3,
  },
  couponButtonText: {
    color: '#fff',
    fontSize: 12,
  },
  menuContainer: {
    flexDirection: 'row',
    backgroundColor: '#fff',
    paddingVertical: 15,
    marginBottom: 10,
  },
  menuItem: {
    flex: 1,
    alignItems: 'center',
  },
  menuText: {
    fontSize: 12,
    marginTop: 5,
    color: '#333',
  },
  sectionContainer: {
    backgroundColor: '#fff',
    padding: 15,
    marginBottom: 10,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    marginBottom: 10,
    color: '#333',
  },
  roomCard: {
    width: 120,
    marginRight: 10,
  },
  roomImage: {
    width: 120,
    height: 90,
    borderRadius: 5,
  },
  roomInfo: {
    padding: 5,
  },
  roomTitle: {
    fontSize: 14,
    color: '#333',
  },
  roomPrice: {
    fontSize: 16,
    color: '#ff4d4f',
    fontWeight: 'bold',
  },
  recommendedCard: {
    flexDirection: 'row',
    marginBottom: 15,
    borderRadius: 5,
    backgroundColor: '#fff',
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.1,
    shadowRadius: 3.84,
    elevation: 5,
  },
  recommendedImage: {
    width: 120,
    height: 90,
    borderRadius: 5,
  },
  recommendedInfo: {
    flex: 1,
    padding: 10,
  },
  recommendedTitle: {
    fontSize: 16,
    color: '#333',
    marginBottom: 5,
  },
  tagsContainer: {
    flexDirection: 'row',
    marginBottom: 5,
  },
  tag: {
    backgroundColor: '#fff1f0',
    paddingHorizontal: 6,
    paddingVertical: 2,
    borderRadius: 3,
    marginRight: 5,
  },
  tagText: {
    fontSize: 12,
    color: '#ff4d4f',
  },
  priceContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  price: {
    fontSize: 20,
    color: '#ff4d4f',
    fontWeight: 'bold',
  },
  iconContainer: {
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: '#E6F7F6',
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: 5,
  },
  bookButton: {
    backgroundColor: '#1890ff',
    paddingHorizontal: 15,
    paddingVertical: 5,
    borderRadius: 3,
  },
  bookButtonText: {
    color: '#fff',
    fontSize: 14,
  },
});

export default HomeScreen; 